#!/bin/bash
set -xeuo pipefail
BASE_DIR=$(cd "$(dirname "$0")"; pwd)
cd ${BASE_DIR}

docker images |grep cypress-allinone ||(
 echo "没有Cyrpess定制的镜像文件"
 exit 1
)

grep -rins '"cypress":' package.json |grep "6.1.0" ||(
 echo "项目使用的cypress版本和镜像不一致"
 exit 2
)

PRJ=`basename $(pwd)`
if [ $(docker ps -a | grep ${PRJ}|wc -l) -eq "1" ]; then
 echo "start ${PRJ}"
 docker start ${PRJ}
else
 echo "run ${PRJ}"
 docker run -itd --name ${PRJ} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY -v $PWD:/e2e --network host -w /e2e --entrypoint=cypress dev.docker:8085/cypress-allinone:6.1.0 open --project .
 
 sleep 5
 docker ps | grep ${PRJ}
fi

#如果需要更换npm源，打开下面这个
docker exec -it ${PRJ} bash -c "npm config set registry https://registry.npm.taobao.org/; yarn config set registry https://registry.npm.taobao.org/"

echo "安装必要的一些nodejs包"
echo "依赖包安装成功后，就可运行了^_^"
docker exec -it ${PRJ} bash -c "[ -d node_modules ] || npm install --verbose"
#启动vscode环境 Enjoy code life!!!
#docker exec -it ${PRJ} bash -c vscode

#启动测试程序的服务和客户端
docker exec -itd ${PRJ} bash -c "npm run start:server"
sleep 2
docker exec -it ${PRJ} bash -c "npm run start:client"

echo "刷新cypress Runner可以运行测试了"
:<<EOF
cypress.json 中可以正常登录的用户 cypress.json:: tester@test.com password1234
EOF

echo "done"
